import scala.actors._
import scala.util.Random

/**
 * BagScan takes the given Bag and passes it to Security if it passes.
 * Rejects Bags 20% of the time.
 * @author Samuel Nelson, Robert Vrooman, James Fitzgerald, Gabriel Marcano
 */

class BagScan(lineNum: Int, security: Security) extends Actor {
  private val _lineNumber = lineNum;
  def lineNumber = _lineNumber
  def act() {
    loop {
      react {
        case bag: Bag =>
          println("BagScan " + lineNum + " has received Bag " + bag.ID + ".")
          // Incoming bags to be checked. Fail them at 20% and send them
          // on to security
          if (Random.nextDouble < .20) {
            val report = new Report(bag.ID, false)
            println("BagScan " + lineNum +
                    " is sending Passenger " + bag.ID + " Bag's failed"+
                    " Report to Security "  + security.lineNumber + ".")
            security ! report
          } else {
            val report = new Report(bag.ID, true)
            println("BagScan " + lineNum +
                    " is sending Passenger " + bag.ID + " Bag's passed"+
                    " Report to Security "  + security.lineNumber + ".")
            security ! report
          }
          
        case Startup =>
          security ! Startup
          
        case Shutdown =>
          println("BagScan " + lineNum + " has received Shutdown.")
          shutdownRequested
      }
    }
  }

  // reactWithin(0) gives a TIMEOUT as soon as the mailbox is empty
  def shutdownRequested: Nothing = reactWithin(0) {
    case Shutdown => {
      shutdownRequested
    }
    case TIMEOUT => {
        println("BagScan " + lineNum + " is sending Shutdown to Security "
                + security.lineNumber + ".")
      security ! Shutdown
      println("BagScan " + lineNum + " has now shutdown.")
      exit
    }
  }
}